const { Op } = require('sequelize');
const Order = require('../model/Order');
const User = require('../model/User');
const Shop = require('../model/Shop');
const Merchandise = require('../model/Merchandise');
// 生成订单编号
const generateOrderNo = async () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  const datePart = `${year}${month}${day}`;

  const latestOrder = await Order.findOne({
    where: {
      no: {
        [Op.like]: `%${datePart}%`
      }
    },
    order: [['no', 'DESC']],
    limit: 1
  });
  console.log(latestOrder, '最新订单');
  
  let newOrderNo = 1;
  
  if (latestOrder) {
    const latestNo = parseInt(latestOrder.no.toString().slice(-4), 10);
    newOrderNo = latestNo + 1;
  }

  return parseInt(`${datePart}${String(newOrderNo).padStart(4, '0')}`, 10);
};

// 更新用户的总支出价格
const updateUserTotalSpent = async (userId, orderPrice) => {
  try {
    const user = await User.findByPk(userId);
    if (user) {
      await user.increment('totalSpent', { by: orderPrice });
      console.log(`用户 ${userId} 的总支出价格更新为 ${user.totalSpent + orderPrice}`);
    } else {
      console.log(`用户 ${userId} 不存在`);
    }
  } catch (error) {
    console.error('更新用户总支出价格时出错:', error);
  }
};

// 更新用户的总收入价格
const updateUserTotalIncome = async (userId, orderPrice) => {
  try {
    const user = await User.findByPk(userId);
    if (user) {
      await user.increment('totalIncome', { by: orderPrice });
      console.log(`用户 ${userId} 的总收入价格更新为 ${user.totalIncome + orderPrice}`);
    } else {
      console.log(`用户 ${userId} 不存在`);
    }
  } catch (error) {
    console.error('更新用户总收入价格时出错:', error);
  }
};

// 添加订单
exports.addOrder = async function (Obj) {
  const orderNo = await generateOrderNo();
  console.log('D' + orderNo, '订单编号');
  const ins = await Order.create({
    no: 'D' + orderNo,
    userId: Obj.userId,
    shopId: Obj.shopId,
    merchandiseId: Obj.merchandiseId,
    orderPrice: +Obj.price,
    info: Obj.info,
    count: +Obj.count,
    orderState: +Obj.state,
    orderType: +Obj.type,
  });
  console.log(ins.toJSON(), '添加成功');

  // 根据订单类型更新用户的总支出或总收入价格
  if (ins.orderType === 0) { // 购买
    await updateUserTotalSpent(ins.userId, ins.orderPrice);
  } else if (ins.orderType === 1) { // 出售
    await updateUserTotalIncome(ins.userId, ins.orderPrice);
  }

  return ins.toJSON();
}
// 查询订单列表
exports.getOrder = async function (uid, shopId, merchandiseId, page = 1, limit = 10, time = '' , keyword = "", orderType) {
  const where = {
    userId: uid,
  };
  console.log(arguments, '参数');
  
  // 添加调试信息
  console.log('Initial query conditions:', where);

  if (shopId) {
    where.shopId = shopId;
  }
  if (merchandiseId) {
    where.merchandiseId = merchandiseId;
  }
  if (time && Array.isArray(time) && time.length === 2) {
    where.createdAt = {
      [Op.gte]: new Date(time[0]),
      [Op.lte]: new Date(time[1]),
    };
  }
  if (keyword) {
    where.info = {
      [Op.like]: `%${keyword}%`,
    };
  }

  if (orderType) {
    where.orderType = orderType;
  }
  // 添加调试信息
  console.log('Final query conditions:', where);

  // 查询商品列表
  const res = await Order.findAndCountAll({
    where,
    offset: (page - 1) * limit,
    limit: +limit,
    include: [ 
      {
        model: Shop,
        as: 'shops',
        attributes: ['id', 'name', 'address'], 
      },
      {
        model: Merchandise,
        as: 'merchandises',
        attributes: ['id', 'name', 'price'], 
      },
    ],
  });

  console.log('Query result:', res);

  return {
    total: res.count,
    data: JSON.parse(JSON.stringify(res.rows)),
  };
}
